import request from '@/utils/request'
import OSS from 'ali-oss';
import store from '@/store'

/**
 * 获取ossClient
 * @param {} option
 * @returns
 */
const getClient = async option => {
  let credit = await request({
    url:'/oss/getCredit',
    method: 'get'
  });
  console.log(option)
  //从后台拿到的临时授权信息
  return {
    client : new OSS({
      region: credit.region,
      accessKeyId: credit.AccessKeyId,
      accessKeySecret: credit.AccessKeySecret,
      stsToken: credit.SecurityToken,
      bucket: credit.bucket,
      secure: true,
    }),
    callback : credit.callback,
  };
}

/**
 / * 上传一个文件
 */
const uploadAction = async option => {
  let {client, callback} = await getClient();
  console.log(option)
  let filePath = '/' + option.fileName;
  //将多个/替换为1个/，防止oss文件路径中多个/造成空目录
  filePath = filePath.replace(/[\/]+/g, '\/');
  // 自定义变量传值
  console.log("uploadUserId=>",store.getters.userId)
  // 自定义函数，对应后端/oss/getCredit接口jasonCallback对象的body
  callback.customValue = {
    uploadUserId: store.getters.userId + '',
    funCode: option.funCode,
    dataId: option.dataId,
    fileOriginalName: option.file.name,
    newFileName: option.newFileName,
    suffixName: option.suffixName,
  };
  callback.contentType = "application/json";
  return client.put(
    filePath,
    option.file, {
      callback: callback,
    }
  )
}

/**
 * 上传多个文件
 * @param {*} files 文件集合
 * @param {*} fileDir oss中文件夹路径
 * @param {*} funCode 自定义参数，功能编号，后端保存时用于区分业务
 * @param {*} dataId 自定义参数，业务主键，后端保存时用于区分工单
 * @param {*} progress
 * @returns oss object路径集合
 */
const uploadFiles = async (files, fileDir, funCode, dataId, progress = console.log) => {
  console.log("files=>",files)
  let urls = [];
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();

  for (let index = 0; index < files.length; index++) {
    let file = files[index];
    let suffixNameIndex = file.name.lastIndexOf('.');
    let suffixName = suffixNameIndex == -1 ? '' : file.name.substring(suffixNameIndex);
    let newFileName =  uuid().replaceAll("-","").toLocaleLowerCase() + suffixName
    let res = await uploadAction({
      //待上传文件信息
      file: files[index],
      //临时访问授权信息
      // token: credit.data,
      // 上传文件名称，为防止文件被覆盖（oss上传重复文件会覆盖同名文件），使用fileDir/年/月/日/uuid.文件后缀，具体可根据实际业务而定

      fileName: `${fileDir}/${year}/${month}/${day}/` + newFileName,
      //可选参数，图片上传过程中触发的操作
      progress: progress,
      funCode: funCode,
      dataId: dataId + '',
      newFileName,
      suffixName: suffixName.length < 1 ? '': suffixName.substr(1),
    });
    if (res.name) {
      urls.push(`${res.name}`);
    }
  }
  //返回多个文件上传结果，为多个oss文件路径地址（不包含host路径）
  return urls;
}

/**
 * 下载文件
 * @param {*} filePath oss object路径
 * @param {*} filename 下载后的文件名
 */
const downloadFile = async (filePath, filename)=>{
  let {client, callback} = await getClient();
  // 配置响应头实现通过URL访问时自动下载文件，并设置下载后的文件名。
  const response = {
    'content-disposition': `attachment; filename=${encodeURIComponent(filename)}`
  }
  // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
  const url = client.signatureUrl(filePath, { response });
  console.log(url);
  return url;
}

function uuid(len, radix) {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  var uuid = [], i;
  radix = radix || chars.length;

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
  } else {
    // rfc4122, version 4 form
    var r;

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random()*16;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
  }

  return uuid.join('');
}

export default {
  upload: uploadFiles,
  getClient: getClient,
  download: downloadFile,
}
